package com.yonyou.mm.controller;

import com.yonyou.mm.aop.ControllerLog;
import com.yonyou.mm.aop.LogUtil;
import com.yonyou.mm.service.ComplexBusinessService;
import com.yonyou.mm.service.TransferService;
import com.yonyou.mm.util.ConstUtil;
import com.yonyou.mm.util.ExceptionUtils4DxyWeb;
import com.yonyou.mm.util.RequestResultDealUtil;
import com.yonyou.mm.util.TestData;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Level;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * Created by yijx on 2017/3/22.
 */
@Controller
public class WorkController {

    /**
     * 查询生产任务备料计划
     */
    @RequestMapping(value = "/taskQuery")
    @ControllerLog(remark = "查询任务")
    public void taskQuery(HttpServletRequest request, HttpServletResponse response) {
        JSONObject param=new JSONObject();
        HttpSession session = request.getSession();
        try {
        	JSONObject resultobj=ComplexBusinessService.queryTaskAndPicks(param, session);
        	RequestResultDealUtil.returnResult(response, null, null, resultobj);
        } catch (Exception e) {
        	RequestResultDealUtil.returnResult(response, "1", e, null);
        }
    }
    
    @RequestMapping(value = "/taskQuery2")
    @ControllerLog(remark = "查询任务")
    public void taskQuery2(HttpServletRequest request, HttpServletResponse response) {
        try {
        	JSONArray result=new JSONArray();
        	JSONObject mat1=new JSONObject();
        	mat1.put("code", "hellocode1");
        	mat1.put("name", "helloname1");
        	JSONObject obj1=new JSONObject();
        	obj1.put("selected", true);
        	obj1.put("mat", mat1);
        	result.add(obj1);
        	JSONObject mat2=new JSONObject();
        	mat2.put("code", "hellocode2");
        	mat2.put("name", "helloname2");
        	JSONObject obj2=new JSONObject();
        	obj2.put("selected", true);
        	obj2.put("mat", mat2);
        	result.add(obj2);
            PrintWriter pw = response.getWriter();
            pw.write(result.toString());
        } catch (Exception e) {
        	ExceptionUtils4DxyWeb.dealException(e);
        }

    }

    /**
     * 查询当日已完成生产任务备料计划
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/doneTaskQuery")
    @ControllerLog(remark = "查询完工生产任务")
    public void doneTaskQuery(HttpServletRequest request, HttpServletResponse response) {

    }

    /**
     * 查询当日备料申请
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/queryReqPickm")
    @ControllerLog(remark = "查询备料申请")
    public void queryReqPickm(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        //传后台数据
        JSONObject info = new JSONObject();
        //站点
        info.put(ConstUtil.POSITION, session.getAttribute(ConstUtil.POSITION));

        //请求类型为保存备料申请
        info.put(ConstUtil.TASKTYPE, "queryReqPickm");

        //回传数据
        JSONObject obj = TransferService.requestService(info,session);
    }

    /**
     * 保存备料申请到后台
     * 前台参数：[{editRowNo:"前台备料申请编辑行号",matBatch:"物料批次",matCode:"物料id",reqNum:"需求数量",reqTime:"送达时限"},{}]
     * 传NC数据：默认参数,ConstUtil.TASKTYPE,POSITION,前台参数
     * 请求NC回传：{result:[{'editRowNo':"前台备料申请编辑行号",'billid':'备料申请id','rowNo':备料申请行号}]}
     * @param request
     * @param response
     */
    @RequestMapping(value = {"/saveReqPickM"})
    @ControllerLog(remark = "保存备料申请")
    public void saveReqPickM(HttpServletRequest request, HttpServletResponse response, @RequestParam HashMap<String, Object> paramData) {
        HttpSession session = request.getSession();
        Object params = paramData.get("data");
        JSONArray jsonarray = JSONArray.fromObject(params);
        //传后台数据
        JSONObject info = new JSONObject();
        //请求类型为保存备料申请
        info.put(ConstUtil.TASKTYPE, "save");
        //备料申请行
        info.put(ConstUtil.ROWS, jsonarray);
        //供应仓
        info.put(ConstUtil.PROVPOS,session.getAttribute(ConstUtil.PROVPOS));
        //站点
        info.put(ConstUtil.POSITION, session.getAttribute(ConstUtil.POSITION));
        //暂存区
        //System.out.println(session.getAttribute(ConstUtil.DESTPOS));
        info.put(ConstUtil.DESTPOS, session.getAttribute(ConstUtil.DESTPOS));
        //回传数据
        JSONObject obj = TransferService.requestService(info,session);
        //请求后台处理

        try {
            PrintWriter pw = response.getWriter();
//            JSONArray vos = JSONArray.fromObject(TestData.reqPickmData);
//            pw.write(vos.toString());
            if (obj.containsKey("result")) {
                JSONArray vos = obj.getJSONArray("result");
                pw.write(vos.toString());
            } else if (obj.containsKey("error")) {
                LogUtil.otherLog(Level.ERROR,obj.get("error"));
                pw.write("error");
            }
        } catch (IOException e) {
        	ExceptionUtils4DxyWeb.dealException(e);
        }

    }

    /**
     * 备料申请完工
     *
     * @param request
     * @param response
     * @param paramData
     */
    @RequestMapping(value = "/doneReqPickm")
    @ControllerLog(remark = "备料申请完工")
    public void doneReqPickm(HttpServletRequest request, HttpServletResponse response, @RequestParam HashMap<String, Object> paramData) {
        HttpSession session = request.getSession();
        JSONObject info =new JSONObject();
        //单据id行号
        info.put(ConstUtil.BILLID,paramData.get(ConstUtil.BILLID));
        info.put(ConstUtil.ROWNO,paramData.get(ConstUtil.ROWNO));
        //请求类型为备料申请完成
        info.put(ConstUtil.TASKTYPE, "done");
        JSONObject result = TransferService.requestService(info,session);
        JSONObject obj = new JSONObject();
        if (result.containsKey("success")) {
            obj.put("flag", 1);
        } else {
            if(result.containsKey("error")) {
                LogUtil.otherLog(Level.ERROR, result.get("error"));
            }
            obj.put("flag", 0);
        }
        try {
            PrintWriter pw = response.getWriter();
            pw.write(obj.toString());
        } catch (IOException e) {
        	ExceptionUtils4DxyWeb.dealException(e);
        }

    }

    /**
     * 领料确认
     *
     * @param request
     * @param response
     * @param paramData
     */
    @RequestMapping(value = "/transConfirm")
    @ControllerLog(remark = "领料确认")
    public void transConfirm(HttpServletRequest request, HttpServletResponse response, @RequestParam HashMap<String, Object> paramData) {
        HttpSession session = request.getSession();
        String transBill = request.getParameter(ConstUtil.TRANSBILLCODE);
        String rowno = request.getParameter(ConstUtil.ROWNO);
        String pk_batchcode = request.getParameter("pk_batchcode");
        String batchcode = request.getParameter("batchcode");
        String weight = request.getParameter("weight");
//        String pk_material = request.getParameter("pk_material");
//        double nnum=Double.parseDouble(request.getParameter("nnum"));
        JSONObject info =new JSONObject();
        info.put(ConstUtil.TRANSBILLCODE,transBill);
        info.put(ConstUtil.ROWNO,rowno);
        info.put("pk_batchcode",pk_batchcode);
        info.put("batchcode", batchcode);
        info.put("weight",weight);
//        info.put("pk_material",pk_material);
//        info.put("nnum",nnum);
        info.put(ConstUtil.TASKTYPE,"confirm");
        info.put(ConstUtil.ORG,session.getAttribute(ConstUtil.ORG));
        info.put(ConstUtil.PROVPOS,session.getAttribute(ConstUtil.PROVPOS));
        info.put(ConstUtil.POSITION,session.getAttribute(ConstUtil.POSITION));
        JSONObject result = TransferService.requestService(info,session);
        
        try {
            PrintWriter pw = response.getWriter();
            pw.write(result.toString());
        } catch (IOException e) {
        	ExceptionUtils4DxyWeb.dealException(e);
        }
    }

    @RequestMapping(value = "/getTransBillInfo")
    @ControllerLog(remark = "根据转库单号获取转库单信息")
    public void getTransBillInfo(HttpServletRequest request, HttpServletResponse response, @RequestParam HashMap<String, Object> paramData) {
    	String transBillCode = request.getParameter(ConstUtil.TRANSBILLCODE);
    	String rowno = request.getParameter(ConstUtil.ROWNO);
        JSONObject info =new JSONObject();
        info.put(ConstUtil.TRANSBILLCODE,transBillCode);
        info.put(ConstUtil.ROWNO,rowno);
        info.put(ConstUtil.TASKTYPE,"getTransBillInfo");
        JSONObject result = TransferService.requestService(info,request.getSession());
        try {
            PrintWriter pw = response.getWriter();
            pw.write(result.toString());
        } catch (IOException e) {
        	ExceptionUtils4DxyWeb.dealException(e);
        }
    }
    /**
     * 根据物料编码查询物料详细信息
     * 前台参数：ConstUtil.MATCODE(物料id)
     * 传CN参数：默认参数,ConstUtil.TASKTYPE,MATCODE
     * NC回传数：{'matid':'物料Id','matCode':'物料编码'," +
     "'matname':'物料名称','matspec':'物料规格','mattype':'物料型号'," +
     "'matBatch':'物料批次号','matunit':'物料单位'}
     * @param request
     * @param response
     * @param paramData
     */
    @RequestMapping(value = "/searchMatFromServer")
    @ControllerLog(remark = "查询物料详细信息")
    public void searchMatFromServer(HttpServletRequest request, HttpServletResponse response, @RequestParam HashMap<String, Object> paramData) {
        HttpSession session = request.getSession();
        JSONObject info =new JSONObject();
        //请求类型为查询物料信息
        info.put(ConstUtil.TASKTYPE, "searchMat");
        //物料编码
        info.put(ConstUtil.MATCODE,paramData.get(ConstUtil.MATCODE));
        JSONObject result = TransferService.requestService(info,session);

//        result = JSONObject.fromObject(TestData.material);
        try {
            PrintWriter pw = response.getWriter();
            pw.write(result.toString());
        } catch (IOException e) {
        	ExceptionUtils4DxyWeb.dealException(e);
        }
    }

    /**
     * 通知轨道车放空车
     *
     * @param request
     * @param response
     * @param paramData
     */
    @RequestMapping(value = "/releaseTruck")
    @ControllerLog(remark = "放空车")
    public void releaseTruck(HttpServletRequest request, HttpServletResponse response, @RequestParam HashMap<String, Object> paramData) {

    }
    
    /**
     * 刷新备料申请列表，从后台查询数据
     * 前台参数：ConstUtil.WAREHOUSE，POSITION
     * 传NC参数：默认参数，ConstUtil.TASKTYPE
     * NC回传：'rows':[{'billid': '备料申请id','rowno':'备料申请汇总行号'," +
     "'cinstockid':'发料仓库','reqTime':'需求时间','position':'需求站点'," +
     "'matname':'物料名称'," + "'matspec':'物料规格','mattype':'物料型号','matBatch':'物料批次','reqNum':'需求数量'," +
     "'matunit':'物料单位'," + "'nacctransnum':'已转库数量','status':'状态'},{}]
     * @param request
     * @param response
     * @param paramsData
     */
    @RequestMapping(value = "/getReqPickm")
    public void getReqPickm(HttpServletRequest request, HttpServletResponse response, @RequestParam HashMap<String,Object> paramsData){
        HttpSession session = request.getSession();
        JSONObject info = new JSONObject();
        info.put("cpickmid", paramsData.get("cpickmid"));
        //添加参数
        //当前站点对应的暂存区
        info.put(ConstUtil.DESTPOS,session.getAttribute(ConstUtil.DESTPOS));
        //当前站点对应的供应仓
        info.put(ConstUtil.PROVPOS,session.getAttribute(ConstUtil.PROVPOS));
        //类型
        info.put(ConstUtil.TASKTYPE,"queryReqPickm");

        //查询结果
        JSONObject result= TransferService.requestService(info,session);

//        JSONArray rows = JSONArray.fromObject(TestData.reqPickmList);
//        result.put("rows",rows);
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write(result.toString());
        } catch (IOException e) {
        	ExceptionUtils4DxyWeb.dealException(e);
        }
    }
    
    /**
     * 刷新转库单，从后台查询数据
     * 前台参数：ConstUtil.WAREHOUSE
     * 传NC参数：默认参数，ConstUtil.TASKTYPE
     */
    @RequestMapping(value = "/getTransBillListComfirm")
    public void getTransBillList(HttpServletRequest request, HttpServletResponse response, @RequestParam HashMap<String,Object> paramsData){
    	HttpSession session = request.getSession();
        JSONObject info = new JSONObject();
        //添加参数
        //当前组织
        info.put(ConstUtil.ORG,session.getAttribute(ConstUtil.ORG));
        //当前站点对应的暂存区
        info.put(ConstUtil.DESTPOS,session.getAttribute(ConstUtil.DESTPOS));
        //类型
        info.put(ConstUtil.TASKTYPE,"getTransBillListComfirm");

        //查询结果
        JSONObject result= TransferService.requestService(info,session);

        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write(result.toString());
        } catch (IOException e) {
        	ExceptionUtils4DxyWeb.dealException(e);
        }
    }
    
    /**
     * 通过转库单生成其他入库单
     * @param request
     * @param response
     * @param paramsData
     */
    @RequestMapping(value = "/toOtherInTransBill")
    public void toOtherOutTransBill(HttpServletRequest request, HttpServletResponse response, @RequestParam HashMap<String,Object> paramsData){
        HttpSession session = request.getSession();
        JSONObject info = JSONObject.fromObject(paramsData.get("info").toString());
        
        //当前组织
        info.put(ConstUtil.ORG,session.getAttribute(ConstUtil.ORG));
        //当前站点对应的供应仓
        info.put(ConstUtil.WAREHOUSE,session.getAttribute(ConstUtil.WAREHOUSE));
        //类型
        info.put(ConstUtil.TASKTYPE,"toOtherInTransBill");
        //System.out.println(info.toString());
        JSONObject result = TransferService.requestService(info,session);
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write(result.toString());
        } catch (IOException e) {
        	ExceptionUtils4DxyWeb.dealException(e);
        }

    }
    
    /**
     * 加载领料确认页面
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/LoadComfirmTrans")
    @ControllerLog(remark = "加载领料确认")
    public String LoadComfirmTrans(HttpServletRequest request, Model model){
        HttpSession session = request.getSession();
        HashMap<String, Object> info = new HashMap<String, Object>();
        info.put(ConstUtil.USERNAME,session.getAttribute(ConstUtil.USERNAME));

        TransferService configutilservice = new TransferService();
        String val  = configutilservice.addWorkTaskAttr(info);
        model.addAttribute("config", JSONObject.fromObject(val));
        String usertype=(String) session.getAttribute(ConstUtil.USERTYPE);
        model.addAttribute("titleinfo","领料确认");
        return "ComfirmTransList";
    }
}